// ************************************************************
// Copyright © 2022
// File Name: main.go
// Author:
// Email:
// Created: 2022-02-05 10:52:43 (CST)
// Last Update:
//          By:
// Description:
// ************************************************************
package main

import (
	"bufio"
	"fmt"
	"goim/packet"
	"net"
)

func handleConn(c net.Conn) {
	defer c.Close()
	rbuf := bufio.NewReader(c)
	wbuf := bufio.NewWriter(c)

	for {
		recvPkt := packet.NewIMPackage()
		err := recvPkt.Decode(rbuf)
		if err != nil {
			fmt.Println("handleConn: packager decode error: ", err)
			return
		}

		recvPkt.Print()

		var message string
		switch recvPkt.Operation {
		case packet.Auth:
			message = "Pass"
		case packet.Heartbeat:
			message = "Live"
		case packet.Message:
			message = "Reply message"
		default:
			message = "Unknown message"
		}

		ackPkt := packet.NewIMPackage()
		ackPkt.Operation = recvPkt.Operation
		ackPkt.ProtocalVer = recvPkt.ProtocalVer
		ackPkt.Body = []byte(message)
		ackPkt.SequenceID = recvPkt.SequenceID
		ackPkt.PackageLen = uint32(20 + len(ackPkt.Body))
		ackPkt.Print()
		err = ackPkt.Encode(wbuf)
		if err != nil {
			fmt.Println("handleConn: reply error ", err)
		}

		wbuf.Flush()
	}
}

func main() {
	l, err := net.Listen("tcp", ":9999")
	if err != nil {
		fmt.Println("Listen err: ", err)
		return
	}
	for {
		c, err := l.Accept()
		if err != nil {
			fmt.Println("accept error: ", err)
			break
		}
		go handleConn(c)
	}
}
